package com.adkun.community.actuator;

import com.adkun.community.util.CommunityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Component
@Endpoint(id = "database")
@Slf4j
public class DatabaseEndPoint {

    private final DataSource dataSource;

    public DatabaseEndPoint(@Qualifier("dataSource") DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * @ReadOpeartion 表示这方法是用GET请求获取的
     * @return
     */
    @ReadOperation
    public String checkConnection() throws SQLException {

        try (
                Connection connection = dataSource.getConnection();
                ) {
            return CommunityUtil.getJSONString(0, "获取连接成功");
        } catch (SQLException e) {
            log.error("获取连接失败" + e.getMessage());
            return CommunityUtil.getJSONString(1, "获取连接失败");
        }
    }
}
